package com.mical.demo.respository;



import com.mical.demo.model.Role;
import com.mical.demo.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Optional;
import java.util.Set;

@Repository
public class UserRepository {
    private final JdbcTemplate template;

    @Autowired
    public UserRepository(JdbcTemplate template) {this.template = template;
    }


    public User findByUsername(String username) {
        try {
            List<User> users = template.query(
                    "SELECT * FROM user WHERE username = ?",
                    new RowMapper<User>() {
                        @Override
                        public User mapRow(ResultSet rs, int rowNum) throws SQLException {
                            return new User(
                                    rs.getLong("id"),
                                    rs.getString("username"),
                                    rs.getString("password"),
                                    rs.getString("nickname"),
                                    rs.getInt("enabled"),
                                    rs.getString("classno"),
                                    rs.getTimestamp("regtime"),
                                    null
                            );
                        }
                    },
                    username
            );

            return users.isEmpty() ? null : users.get(0);

        } catch (EmptyResultDataAccessException e) {
            // spring.jdbc 5.3+ 已弃用此异常的情况
            return null;
        }
    }



    public Set<Role> findRolesByUserId(Long userId) {
        return template.query(
                "SELECT r.* FROM role r JOIN user_role ur ON r.id = ur.r_id WHERE ur.u_id = ?",
                (ResultSet rs, int rowNum) -> new Role(
                        rs.getLong("id"),
                        rs.getString("name"),
                        rs.getString("note")
                ),
                userId
        ).stream().collect(java.util.stream.Collectors.toSet());
    }

    public void save(User user) {

    }
}